﻿using System.Collections;
using System.Drawing.Printing;
using System.IO;
using Coffee_Restaurant.DAL;
using Coffee_Restaurant.Database;
using Coffee_Restaurant.Forms.Items;
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Coffee_Restaurant.Models;
using MetroFramework;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using BorderStyle = NPOI.SS.UserModel.BorderStyle;
using HorizontalAlignment = NPOI.SS.UserModel.HorizontalAlignment;

namespace Coffee_Restaurant.Forms.InOutMoneys
{
    public partial class ManagerInOutMoneys : Form
    {

        public ManagerInOutMoneys()
        {
            InitializeComponent();

        }


        void itemAdd_BtnAdd()
        {
            LoadItems(null);
        }

        private void ManagerInOutMoney_Load(object sender, EventArgs e)
        {
            //set time tim kiem  trong thang
            DateTime date = DateTime.Now;
            dateTimeFrom.Value = new DateTime(date.Year, date.Month, 1, 0, 0, 0, 0); //00hAM ngay m1
            dateTimeTo.Value = new DateTime(date.Year, date.Month, date.Day, 23, 59, 0, 0); // 24h00 ngay hien tai
            LoadItems(null);

        }



        /// <summary>
        /// load data to datagridview
        /// </summary>
        /// <param name="group"></param>
        public void LoadItems(string group)
        {
            using (var db = new DatabaseEntities())
            {
                //clear trc khi load
                dataGridViews.Rows.Clear();
                //mac dinh la load tat ca
                var model = db.InOutMoneys.Where(x => x.Datetime >= dateTimeFrom.Value && x.Datetime <= dateTimeTo.Value).ToList();
                if (!string.IsNullOrEmpty(group))
                {
                    //tim theo group
                    if (group.Contains("nợ"))
                    {
                        model = db.InOutMoneys.Where(x => x.Type.Contains("nợ") && (x.Datetime >= dateTimeFrom.Value && x.Datetime <= dateTimeTo.Value)).ToList();
                    }
                    else
                    {
                        model = db.InOutMoneys.Where(x => x.Group == group && (x.Datetime >= dateTimeFrom.Value && x.Datetime <= dateTimeTo.Value)).ToList();
                    }
                }
                for (int i = 0; i < model.Count; i++)
                {
                    var item = model[i];
                    var row = new object[dataGridViews.ColumnCount];
                    row[0] = DateTime.Parse(item.Datetime.ToString()).ToString("HH:mm:ss dd/mm/yyyy");
                    row[1] = item.Type;
                    row[2] = item.Description;
                    row[3] = item.Money;
                    row[4] = item.ByName;
                    dataGridViews.Rows.Insert(i, row);
                }

                foreach (DataGridViewRow row in dataGridViews.Rows)
                {
                    if ((string)row.Cells["Type"].Value == "Nhập kho")
                    {
                        row.DefaultCellStyle.ForeColor = System.Drawing.Color.MidnightBlue;
                    }
                    else if (row.Cells["Type"].Value.ToString().Contains("nợ"))
                    {
                        row.DefaultCellStyle.ForeColor = System.Drawing.Color.Red;
                    }
                    else
                    {
                        row.DefaultCellStyle.ForeColor = System.Drawing.Color.Maroon;
                    }
                }

                dataGridViews.ClearSelection(); // disable auto selected row
            }

        }


        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        //esc to exit
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.F5)
            {
                LoadItems(null);
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }


        #region rightmenuItems
        private void toolStripMenuItemLoadItems_Click(object sender, EventArgs e)
        {
            LoadItems(null);
        }

        private void toolStripMenuItemAdd_Click(object sender, EventArgs e)
        {
            var itemAdd = new AddInOutMoney();
            itemAdd.BtnAdd += itemAdd_BtnAdd;
            itemAdd.ShowDialog();
        }

        private void toolStripMenuItemDelete_Click(object sender, EventArgs e)
        {
            CustomMessageBox.Show("Bạn không thể xóa vì hệ thống đã tự động thống kê doanh số", "", "alert", MetroColorStyle.Default);
        }

        private void toolStripMenuItemEdit_Click(object sender, EventArgs e)
        {
            CustomMessageBox.Show("Bạn không thể xóa vì hệ thống đã tự động thống kê doanh số", "", "alert", MetroColorStyle.Default);
        }

        #endregion

        /// <summary>
        /// select ItemId for edit and delete
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewItems_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //select header column thi index = -1 => exception
            if (e.RowIndex >= 0)
            {
                //ItemIdSelect = dataGridViews.Rows[e.RowIndex].Cells["ItemId"].Value.ToString();
            }
        }

        #region filersearch
        private void btnAll_Click(object sender, EventArgs e)
        {
            lblHeading.Text = "Tất cả giao dịch";
            LoadItems(null);
        }

        private void btnIn_Click(object sender, EventArgs e)
        {
            lblHeading.Text = "Giao dịch thu";
            LoadItems("Thu");
        }

        private void btnOut_Click(object sender, EventArgs e)
        {
            lblHeading.Text = "Giao dịch chi";
            LoadItems("Chi");
        }

        private void btnOwe_Click(object sender, EventArgs e)
        {
            lblHeading.Text = "Giao dịch nợ";
            LoadItems("nợ");
        }
        #endregion

        public DateTime BeginDate;
        public DateTime EndDate;

        /// <summary>
        /// tim kiem theo thoi gian
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dateTimeFrom_ValueChanged(object sender, EventArgs e)
        {
            BeginDate = dateTimeFrom.Value;
        }

        private void dateTimePickerTo_ValueChanged(object sender, EventArgs e)
        {
            EndDate = dateTimeTo.Value;
        }

        private void btnExportExcel_Click(object sender, EventArgs e)
        {
            String title = string.Format("Báo cáo thu chi ({0}) từ ngày {1} - {2}", lblHeading.Text, dateTimeFrom.Value, dateTimeTo.Value);
            const string folder = "baocao";
            string filename = @"" + folder + "/Baocaothuchi-" + DateTime.Now.ToString("dd-MM-yyyy") + ".xls";
            Export.InitializeWorkbook();
            Export.GenerateData(title, dataGridViews);
            Export.WriteToStream(filename, folder);
        }


        private void btnPrint_Click(object sender, EventArgs e)
        {

            //Open the print preview dialog
            String title = string.Format("Báo cáo thu chi ({0}) từ ngày {1} - {2}", lblHeading.Text, dateTimeFrom.Value, dateTimeTo.Value);
            PrintHelper.titleDoc = title;

            //event print
            PrintHelper.dataGridViews = dataGridViews;
            printDocument1.BeginPrint += PrintHelper.printDocument1_BeginPrint;
            printDocument1.PrintPage += PrintHelper.printDocument1_PrintPage;
            printDocument1.DocumentName = title;


            var objPPdialog = new PrintPreviewDialog();
            objPPdialog.ShowIcon = false;
            objPPdialog.Document = printDocument1;
            objPPdialog.WindowState = FormWindowState.Maximized;
            objPPdialog.Document.DefaultPageSettings.PrinterSettings.PrinterName = PrinterDa.GetDefaultPrinter(1);
            objPPdialog.ShowDialog();
        }
    }
}
